package com.hulman.oms.service;

import com.github.benmanes.caffeine.cache.Cache;

import com.hulman.oms.bean.WeApiResult;
import com.hulman.oms.dao.ContactDao;
import com.hulman.oms.dao.UserDao;
import com.hulman.oms.exception.IoTException;
import com.hulman.oms.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 企业微信联系人服务
 */
@Service
public class ContactService
{
    public static final String CONTACT_TOKEN = "contact-token";

    @Autowired
    private ContactDao contactDao;
    @Autowired
    private Cache<String, String> tokenCache;

    public String getAccessToken()
    {
        String token = tokenCache.getIfPresent(CONTACT_TOKEN);
        if (! StringUtil.isEmpty(token))
        {
            return token;
        } else
        {
            token = contactDao.getAccessToken();
            tokenCache.put(CONTACT_TOKEN, token);
            return token;
        }
    }

    public void addContact(String userId, String name, String mobile, String position)
    {
        String accessToken = getAccessToken();
        Map<String, Object> contact = new LinkedHashMap<>();
        contact.put("department", new int[]{1});//根部门
        contact.put("userid", userId);
        contact.put("name", name);
        contact.put("mobile", mobile);
        contact.put("position", position);
        WeApiResult result = contactDao.create(accessToken, contact);
        if (result.getErrCode() != 0)
        {
            throw new IoTException(result.getErrMsg());
        }
    }

    public void updateContact(String userId, String name, String mobile, String position)
    {
        String accessToken = getAccessToken();
        Map<String, Object> contact = new LinkedHashMap<>();
        contact.put("userid", userId);
        contact.put("name", name);
        contact.put("mobile", mobile);
        contact.put("position", position);
        WeApiResult result = contactDao.update(accessToken, contact);
        if (result.getErrCode() != 0)
        {
            throw new IoTException(result.getErrMsg());
        }
    }

    /**
     * 同步账号（插入或更新）
     *
     * @param userId
     * @param name
     * @param mobile
     * @param position
     */
    public void syncContact(String userId, String name, String mobile, String position)
    {
        String accessToken = getAccessToken();
        Map<String, Object> contact = new LinkedHashMap<>();
        contact.put("department", new int[]{1});//根部门
        contact.put("userid", userId);
        contact.put("name", name);
        contact.put("mobile", mobile);
        contact.put("position", position);
        WeApiResult result = contactDao.create(accessToken, contact);
        contact.remove("department");//不更新部门信息
        //60104：手机号码已存在
        if (result.getErrCode() == 60104)
        {
            //查到手机号对应的userId
            String oldUserId = findUserIdByMobile(mobile);
            //企业微信userId与系统账号不一致，则更新企业微信userId
            if (! userId.equals(oldUserId))
            {
                contact.put("userid", oldUserId);//老用户ID
                contact.put("new_userid", userId);//新用户ID
            }
            result = contactDao.update(accessToken, contact);
            if (result.getErrCode() != 0)
            {
                throw new IoTException(result.getErrMsg());
            }
        } //60102：userId已存在，则更新信息
        else if (result.getErrCode() == 60102)
        {
            result = contactDao.update(accessToken, contact);
            if (result.getErrCode() != 0)
            {
                throw new IoTException(result.getErrMsg());
            }
        } else if (result.getErrCode() != 0)
        {
            throw new IoTException(result.getErrMsg());
        }
    }

    public void deleteContact(String userId)
    {
        String accessToken = getAccessToken();
        contactDao.delete(accessToken, userId);
    }

    /**
     * 根据手机号查询userid
     *
     * @param mobile
     * @return
     */
    public String findUserIdByMobile(String mobile)
    {
        String accessToken = getAccessToken();
        Map<String, Object> contact = new LinkedHashMap<>();
        contact.put("mobile", mobile);
        WeApiResult result = contactDao.getUserId(accessToken, contact);
        if (result.getErrCode() != 0)
        {
            throw new IoTException(result.getErrMsg());
        }
        return (String) result.getData().get("userid");
    }
}
